package net.maku.module.service;

import net.maku.module.entity.AgStockDataDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

@Service
public class StockService {

    @Value("${gp.gpapi}")
    private String urls;
    
    @Autowired
    private CacheManager cacheManager;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    // 记录最后更新时间，用于定时刷新
    private final Map<String, Long> lastUpdateTime = new ConcurrentHashMap<>();
    
    // 正在更新的股票代码锁
    private final Map<String, Boolean> updatingStocks = new ConcurrentHashMap<>();
    
    /**
     * 同步获取股票数据
     */
    public AgStockDataDTO fetchStockData(String stockCode) {
        try {
            String url = urls + "/list=" + stockCode;
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("Referer", "https://finance.sina.com.cn");
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class);
            
            System.out.println("同步获取股票数据: " + stockCode + ", 响应: " + response.getBody());
            AgStockDataDTO agStockDataDTO = parseStockData(response.getBody());
            
            // 记录更新时间
            if (agStockDataDTO != null) {
                lastUpdateTime.put(stockCode, System.currentTimeMillis());
            }
            
            return agStockDataDTO;
            
        } catch (Exception e) {
            System.err.println("获取股票数据失败: " + stockCode + ", 错误: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 异步更新股票数据
     */
    @Async
    public void asyncUpdateStockData(String stockCode) {
        // 防止重复更新
        if (updatingStocks.putIfAbsent(stockCode, true) != null) {
            return;
        }
        
        try {
            System.out.println("开始异步更新股票数据: " + stockCode);
            AgStockDataDTO newData = fetchStockData(stockCode);
            
            if (newData != null) {
                Cache cache = cacheManager.getCache("stockData");
                if (cache != null) {
                    cache.put(stockCode, newData);
                    System.out.println("异步更新股票数据成功: " + stockCode);
                }
            }
        } catch (Exception e) {
            System.err.println("异步更新股票数据失败: " + stockCode + ", 错误: " + e.getMessage());
        } finally {
            updatingStocks.remove(stockCode);
        }
    }
    
    /**
     * 定时刷新缓存中的数据（每5分钟执行一次）
     */
    @Scheduled(fixedRate = 300000) // 5分钟
    public void scheduledRefreshCache() {
        Cache cache = cacheManager.getCache("stockData");
        if (cache == null) return;

        // 获取缓存中的所有股票代码（这里需要根据实际缓存实现调整）
        // 如果是ConcurrentMapCache，可以通过原生缓存获取keys
        System.out.println("开始定时刷新股票数据缓存，时间: " + new Date());

        // 遍历所有缓存的股票代码进行更新
        updatingStocks.keySet().forEach(stockCode -> {
            // 只更新最近5分钟内没有更新过的数据
            Long lastUpdate = lastUpdateTime.get(stockCode);
            if (lastUpdate == null || System.currentTimeMillis() - lastUpdate > 300000) {
                asyncUpdateStockData(stockCode);
            }
        });
    }
    
    /**
     * 手动刷新指定股票数据
     */
    public void refreshStockData(String stockCode) {
        asyncUpdateStockData(stockCode);
    }
    
    /**
     * 解析股票数据（你的原有解析逻辑）
     */
    private AgStockDataDTO parseStockData(String responseData) {
        // 解析返回的 API 数据
        String[] stockData = responseData.split("=")[1].replace(";", "").trim().split(",");

        AgStockDataDTO agStockDataDTO = new AgStockDataDTO();

        // 解析当前价格
        agStockDataDTO.setCurrentPrice(Double.parseDouble(stockData[3]));

        // 计算涨跌金额，并截取两位小数
        BigDecimal priceChange = new BigDecimal(agStockDataDTO.getCurrentPrice() - Double.parseDouble(stockData[2])).setScale(2, RoundingMode.HALF_UP);
        agStockDataDTO.setPriceChange(priceChange.doubleValue());

        // 计算涨跌比，并截取两位小数
        BigDecimal priceChangeRatio = new BigDecimal((priceChange.doubleValue() / Double.parseDouble(stockData[2])) * 100).setScale(2, RoundingMode.HALF_UP);
        agStockDataDTO.setPriceChangeRatio(priceChangeRatio.doubleValue());

        agStockDataDTO.setVolume(Integer.parseInt(stockData[8]) / 100); // 成交量（手）

        // 成交额（万元），四舍五入到整数
        BigDecimal amount = new BigDecimal(Double.parseDouble(stockData[9]) / 10000).setScale(0, RoundingMode.HALF_UP);
        agStockDataDTO.setAmount(amount.intValue());

        agStockDataDTO.setOpenPrice(Double.parseDouble(stockData[1])); // 今日开盘价
        agStockDataDTO.setPreviousClosePrice(Double.parseDouble(stockData[2])); // 昨日收盘价
        agStockDataDTO.setHighPrice(Double.parseDouble(stockData[4])); // 今日最高价
        agStockDataDTO.setLowPrice(Double.parseDouble(stockData[5])); // 今日最低价

        return agStockDataDTO;
    }
}